<script setup lang="ts">
  import {
    useGetReceivePaymentDetail,
    useGetReceivePaymentDetailOrderList,
  } from '@/services/pages/withdrawal/receive-payment/useReceivePayment'
  import { TableColumnCtx } from 'element-plus'
  import { watch } from 'vue'
  import { useRouter } from 'vue-router'

  interface SummaryMethodProps {
    columns: TableColumnCtx<WithdrawalReceivePayment>[]
    data: WithdrawalReceivePayment[]
  }

  const { detail, getDetailLoading, getDetail } = useGetReceivePaymentDetail()
  const { orderList, getOrderListLoading, getOrderList } = useGetReceivePaymentDetailOrderList()

  defineOptions({
    name: 'ReceivePaymentDetailModal',
  })

  const props = defineProps({
    receivePaymentId: {
      type: String,
      required: true,
    },
  })

  // 全局路由对象
  const router = useRouter()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  /**
   * 关闭事件
   */
  const onClose = () => {
    visible.value = false
  }

  /**
   * 获取合计
   * @param param - 参数
   */
  const getSummaries = (param: SummaryMethodProps) => {
    const result: Array<string> = []
    param.columns.forEach((column, index) => {
      // 服务费合计
      if (index === 2) {
        result[2] = `￥${orderList.value
          .map((item) => Number(item.serviceTotalFee))
          .reduce((prev, current) => prev + current, 0)
          .toFixed(2)}`
      }

      // 物料费合计
      if (index === 3) {
        result[3] = `￥${orderList.value
          .map((item) => Number(item.spareTotalFee))
          .reduce((prev, current) => prev + current, 0)
          .toFixed(2)}`
      }

      // 总费用
      if (index === 4) {
        let totalFee = 0
        orderList.value.forEach((item, index) => {
          totalFee += Number(calcRowTotalFee(index))
        })
        result[4] = `￥${totalFee.toFixed(2)}`
      }
    })
    return result
  }

  /**
   * 公司名点击事件
   * @param {string} userId - 公司id
   */
  const handleUsernameClick = (userId: string) => {
    visible.value = false
    router.push({ path: `/user/userdetail/${userId}` })
  }

  /**
   * 工单单号点击事件
   * @param {string} orderId - 工单id
   */
  const handleOrderNoClick = (orderId: string) => {
    visible.value = false
    router.push(`/order/odetail/${orderId}`)
  }

  /**
   * 计算某一行的总费用
   * @param {number} index - 行索引
   */
  const calcRowTotalFee = (index: number) => {
    const receiptPayment = orderList.value[index]
    const materialFee = receiptPayment.spareTotalFee || 0
    const serviceFee = receiptPayment.serviceTotalFee || 0
    const total = materialFee + serviceFee
    return Number((total || 0).toFixed(0)).toFixed(2)
  }

  watch(visible, (value) => {
    if (value && props.receivePaymentId) {
      getDetail(props.receivePaymentId)
      getOrderList(props.receivePaymentId)
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    :width="1100"
    unit="px"
    :loading="getDetailLoading || getOrderListLoading"
    title="收款单详情"
  >
    <div>
      <div class="info-list">
        <div class="info">
          <div class="info-item">
            <div class="label">送修公司：</div>
            <div class="value">
              <h-link @click="handleUsernameClick(detail.repairCompanyUserId)">
                {{ detail.repairCompanyUser }}
              </h-link>
            </div>
          </div>
          <div class="info-item">
            <div class="label">送修人员：</div>
            <div class="value">
              <h-link @click="handleUsernameClick(detail.sendForRepairUserId)">
                {{ detail.sendForRepairUsername }}
              </h-link>
            </div>
          </div>
          <div class="info-item">
            <div class="label">联系电话：</div>
            <div class="value">{{ detail.sendForRepairPhone }}</div>
          </div>
        </div>

        <div class="info">
          <div class="info-item">
            <div class="label">收款单号：</div>
            <div class="value">{{ detail.receivePaymentNo }}</div>
          </div>
          <div class="info-item">
            <div class="label">单据日期：</div>
            <div class="value">{{ detail.receivePaymentCreateTime }}</div>
          </div>
        </div>

        <div class="info">
          <div class="info-item">
            <div class="label">制单人：</div>
            <div class="value">{{ detail.createEmp }}</div>
          </div>
          <div class="info-item">
            <div class="label">审核人：</div>
            <div class="value">{{ detail.checkEmp }}</div>
          </div>
        </div>

        <div class="info">
          <div class="info-item">
            <div class="label">审核备注：</div>
            <div class="value">{{ detail.checkRemark }}</div>
          </div>
          <div class="info-item">
            <div class="label">申请备注：</div>
            <div class="value">{{ detail.remark }}</div>
          </div>
        </div>
      </div>

      <div>
        <div class="title-priamry mb-6px">关联工单</div>
        <el-table :data="orderList" :border="true" :summary-method="getSummaries" show-summary>
          <!-- 序号 -->
          <el-table-column type="index" width="50" :align="'center'" fixed="left" label="序号" />

          <!-- 工单单号 -->
          <el-table-column width="140" show-overflow-tooltip prop="workNo" label="工单单号">
            <template #default="{ row }">
              <h-link @click="handleOrderNoClick(row.workId)">{{ row.workNo }}</h-link>
            </template>
          </el-table-column>

          <!-- 服务费 -->
          <el-table-column width="100" label="服务费">
            <template #default="{ row }">
              ￥{{ (Number(row['serviceTotalFee']) || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 物料费 -->
          <el-table-column width="100" label="物料费">
            <template #default="{ row }">
              ￥{{ (Number(row['spareTotalFee']) || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 总费用 -->
          <el-table-column width="100" label="总费用">
            <template #default="{ $index }"> ￥{{ calcRowTotalFee($index) }} </template>
          </el-table-column>

          <!-- 开票类型 -->
          <el-table-column width="110" label="开票类型">
            <template #default="{ row }">
              <template v-if="row.ticketType === 1">增值税普通发票</template>
              <template v-if="row.ticketType === 2">增值税专用发票</template>
            </template>
          </el-table-column>

          <!-- 抬头类型 -->
          <el-table-column width="80" label="抬头类型">
            <template #default="{ row }">
              <template v-if="row.headType === 1">企业</template>
              <template v-if="row.headType === 2">个人</template>
            </template>
          </el-table-column>

          <!-- 收款凭证 -->
          <el-table-column width="80" label="收款凭证">
            <template #default="{ row }">
              <h-image
                v-if="row.userPaymentVoucher"
                :src="row.userPaymentVoucher"
                :width="50"
                :height="37.5"
                :padding="2"
                :show-del-btn="false"
              />
            </template>
          </el-table-column>

          <!-- 发票抬头 -->
          <el-table-column width="120" show-overflow-tooltip prop="header" label="发票抬头" />

          <!-- 完成时间 -->
          <el-table-column width="128" prop="orderEndTime" label="完成时间"></el-table-column>

          <!-- 发票状态 -->
          <el-table-column width="100" label="发票状态">
            <template #default="{ row }">
              <h-status v-if="row.openTicket">已申请开票</h-status>
              <h-status v-else type="warning">未申请开票</h-status>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <h-button is-modal @click="onClose">关闭</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  :deep(.el-textarea__inner) {
    height: 100px !important;
  }

  .info-list {
    display: flex;
    margin-bottom: 12px;
    column-gap: 32px;

    .info {
      display: flex;
      flex-direction: column;
      row-gap: 4px;

      .info-item {
        display: flex;

        .label {
          color: #606266;
        }

        .value {
          max-width: 300px;
          word-break: break-all;
        }
      }
    }
  }
</style>
